package 多线程交替打印ABC;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author dexi.che on 2021/7/24  10:57 下午
 */
public class SolutionCondition {
    private static Lock lock = new ReentrantLock();
    private static Condition conditionA = lock.newCondition();
    private static Condition conditionB = lock.newCondition();
    private static Condition conditionC = lock.newCondition();
    private static Integer state = 0;

    static class ThreadA implements Runnable {
        @Override
        public void run() {
            try {
                lock.lock();
                for (int i = 0; i < 10; ) {
                    while (state %3 != 0){
                        conditionA.await();
                    }
                    System.out.println("A");
                    state++;
                    conditionB.signal();
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
    static class ThreadB implements Runnable {
        @Override
        public void run() {
            try {
                lock.lock();
                for (int i = 0; i < 10; ) {
                    while (state %3 != 1){
                        conditionB.await();
                    }
                    state++;
                    i++;
                    System.out.println("B");
                    conditionC.signal();
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
    static class ThreadC implements Runnable {
        @Override
        public void run() {
            try {
                lock.lock();
                for (int i = 0; i < 10; ) {
                    while (state %3 != 2){
                        conditionC.await();
                    }
                    state++;
                    i++;
                    System.out.println("C");
                    conditionA.signal();
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        new Thread(new ThreadA()).start();
        new Thread(new ThreadB()).start();
        new Thread(new ThreadC()).start();
    }
}
